
//
//  MaintenanceController.m
//  PropertyMananger
//
//  Created by bh on 17/2/8.
//  Copyright © 2017年 BH. All rights reserved.
//

#import "MaintenanceController.h"
#import "EquipmentQueryCell.h"
#import "MaintenanceDetailController.h"
#import "MaintenanceModel.h"

@interface MaintenanceController ()

@property (nonatomic,strong) NSMutableArray * maintenanceArray;

@property (nonatomic,strong) NSMutableArray * maintenanceResultArr;

@end

@implementation MaintenanceController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initTitleViewName:@"设备保养"];
    
    
    [self initTableViewWithView:self.view frame:CGRectMake(0, 50, BHscreenW, BHscreenH -64 -50) isGroup:NO];
    self.tableView.showsVerticalScrollIndicator = NO;
    
     [self setupSearchBar];
    
    self.maintenanceArray = [[NSMutableArray alloc]init];
    self.maintenanceResultArr = [[NSMutableArray alloc]init];
    
    [self createRefresh];
    
    [self createPlaceHolder];
    
    [self postMaintenancePlanData];
    
}
#pragma mark - 创建刷新UI
- (void)createRefresh{
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        self.nextPage = 1;
        
        self.isDown = YES;
        //获取数据
        [self postMaintenancePlanData];
        
    }];
    
    //上拉刷新
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        self.nextPage += 1;
        
        self.isDown = NO;
        //获取数据
        [self postMaintenancePlanData];
        
        //    [self.tableView.mj_footer endRefreshingWithNoMoreData];
        
    }];
}
#pragma mark - 暂未图
- (void)createPlaceHolder
{
    
    self.placehoderImg = [[UIImageView alloc]init];
    [self.tableView addSubview:self.placehoderImg];
    self.placehoderImg.image = [UIImage imageNamed:@"ico_query_no"];
    
    [self.placehoderImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.tableView).with.offset(0);
        make.top.equalTo(self.tableView.mas_bottom).with.offset(100);
        make.size.mas_equalTo(CGSizeMake(80, 80));
    }];
    
    self.titleLabel = [[UILabel alloc]init];
    [self.tableView addSubview:self.titleLabel];
    self.titleLabel.text = @"暂无查询内容";
    
    self.titleLabel.textColor= BHColor(153, 153, 153);
    self.titleLabel.font = BHFont(15);
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.tableView).with.offset(0);
        make.top.equalTo(self.placehoderImg.mas_bottom).with.offset(10);
        make.size.mas_equalTo(CGSizeMake(100, 25));
    }];
    
}

#pragma mark - 搜索框
- (void)setupSearchBar
{
    self.searchBar = [[MCSearchBar alloc] initWithFrame:CGRectMake(15, 7.5, BHscreenW - 30, 35) placeholder:nil];
    self.searchBar.delegate = self;
    self.searchBar.placeholder = @"请输入设备名称";
    self.searchBar.barTintColor = BHColor(237, 237, 237);
    [self.view addSubview:self.searchBar];
    [self.searchBar setBackgroundColor:BHColor(237, 237, 237)];
    self.searchBar.layer.cornerRadius = 18.0f;
    self.searchBar.layer.masksToBounds = YES;
    self.searchBar.layer.borderWidth = 0.5;
    self.searchBar.layer.borderColor = BHColor(237, 237, 237).CGColor;
    self.searchBar.backgroundColor = BHColor(237, 237, 237);
    self.searchText = @"";
    
    self.searchBar.searchBarStyle = UISearchBarStyleDefault;
    
}
#pragma mark - 搜索框代理方法
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    if (range.location == 0) {
        
        [self.resultArr removeAllObjects];
        [self.tableView reloadData];
        
//        self.placehoderImg.hidden = NO;
//        self.placehoderImg.hidden = NO;
    }
    return YES;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    if (searchText.length == 0) {
        self.searchText = @"";
        self.isSearch = NO;
        
        [self.maintenanceArray removeAllObjects];
        [self.maintenanceResultArr removeAllObjects];
        
        [self.tableView reloadData];
        
        [self.tableView.mj_header beginRefreshing];
        
        self.placehoderImg.hidden = NO;
        self.titleLabel.hidden = NO;
    }
//    else{
//        [self.tableView.mj_header beginRefreshing];
//    }
    
    self.searchStr = searchText;
    [self.resultArr removeAllObjects];
    [self.maintenanceArray removeAllObjects];
    
    [self.tableView reloadData];
    
    
    for (MaintenanceModel * model in self.maintenanceArray) {
        if ([model.EquipmentName rangeOfString:searchText].location != NSNotFound) {
         //   [self.resultArr addObject:model.EquipmentName];
            [self.maintenanceResultArr addObject:model];
        }
        
    }
    
    if (self.resultArr.count != 0) {
        self.isSearch = YES;
        self.placehoderImg.hidden = YES;
        self.titleLabel.hidden = YES;
        [self.tableView reloadData];
    }
    
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    
    return YES;
    
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
    self.isDown = YES;
    
    [self.tableView.mj_header beginRefreshing];

    [self postMaintenancePlanData];
    
    [self.view endEditing:YES];
    
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    
    self.isDown = YES;
    [self.maintenanceResultArr removeAllObjects];
  //  [self postMaintenancePlanData];
    
    [self.searchBar resignFirstResponder];
    
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    
    self.isDown = YES;
    self.nextPage = 1;

    [self postMaintenancePlanData];
    
    self.isSearch = NO;
    
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.view endEditing:YES];
    [self.tableView endEditing:YES];
    self.isSearch = NO;
    
}
#pragma mark - tableview代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (self.isSearch) {
        return self.maintenanceResultArr.count;
    }else{
        return self.maintenanceArray.count;
    }
    return 0;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    EquipmentQueryCell * cell = [EquipmentQueryCell cellWithTableView:tableView];
    
    if (self.isSearch) {
        
         MaintenanceModel * model = self.maintenanceResultArr[indexPath.section];
        
        cell.equipmentCodeLabel.text = [NSString stringWithFormat:@"设备编号:%@",model.EquipmentNumber];
        cell.equipmentNameLabel.text = model.EquipmentName;
        cell.equipmentTypeLabel.text = model.SpecificationModel;
        cell.equipmentStatusLabel.text = model.MaintenancePlanningStatusItemName;
        cell.equipmentInstallLabel.text = model.MaintenanceCategoryItemName;
        
        cell.equipmentStatus.text = @"计划状态:";
        cell.equipmentInstall.text = @"保养类别:";
        
    }else{
    
        MaintenanceModel * model = self.maintenanceArray[indexPath.section];
        
        cell.equipmentCodeLabel.text = [NSString stringWithFormat:@"设备编号:%@",model.EquipmentNumber];
        cell.equipmentNameLabel.text = model.EquipmentName;
        cell.equipmentTypeLabel.text = model.SpecificationModel;
        cell.equipmentStatusLabel.text = model.MaintenancePlanningStatusItemName;
        cell.equipmentInstallLabel.text = model.MaintenanceCategoryItemName;
        
        cell.equipmentStatus.text = @"计划状态:";
        cell.equipmentInstall.text = @"保养类别:";
    }
    
    
   
    
    return cell;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 210;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 15;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    MaintenanceDetailController * detailVC = [[MaintenanceDetailController alloc]init];
    detailVC.model = self.maintenanceArray[indexPath.section];
    [self.navigationController pushViewController:detailVC animated:YES];

}
#pragma mark - 数据请求
- (void)postMaintenancePlanData{
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = @"努力加载数据中...";
    // 隐藏时从父控件中移除
    hud.removeFromSuperViewOnHide = YES;
    hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.userInteractionEnabled = YES;
    
    NSDictionary * parms = nil;
    if (self.searchStr != nil) {
        
        parms =  @{
                   @"CId":userModel.CommunityID,
                   @"EquipmentName":self.searchStr,
                   @"Page":[NSString stringWithFormat:@"%ld",self.nextPage],
                   @"json":@"\{\"jsonEntity\":\{},\"action\":\"findequipmentmaintenanceplan\",\"version\":\"V1.0\"}"
                   };
        
    }else{
        
        parms =  @{
                   @"CId":userModel.CommunityID,
                   @"EquipmentName":@"",
                   @"Page":[NSString stringWithFormat:@"%ld",self.nextPage],
                   @"json":@"\{\"jsonEntity\":\{},\"action\":\"findequipmentmaintenanceplan\",\"version\":\"V1.0\"}"
                   };
        
    }
    
    DLog(@"提交的参数 === %@",parms);
    
    [HomeNetWorkRequest postMaintenancePlanSuccess:^(id data) {
        
        [MBProgressHUD hideHUDForView:self.view];
        
        if (self.isDown == YES) {
            
            [self.maintenanceArray removeAllObjects];
            [self.maintenanceResultArr removeAllObjects];
            self.isDown = NO;
        }
        
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSString * str = [NSString stringWithFormat:@"%@",dict[@"Data"]];
        NSData * data2 = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSArray * array = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
        DLog(@"返回 === %@",dict[@"Code"]);
        DLog(@"返回提示 === %@",dict[@"Msg"]);
        DLog(@"设备保养数据 == %@",array);
        
        for (NSDictionary * dict in array) {
            
            MaintenanceModel * model = [[MaintenanceModel alloc]init];
            [model setValuesForKeysWithDictionary:dict];
            [self.maintenanceArray addObject:model];
            
        }
        
        if (self.maintenanceArray.count != 0){
            
            self.placehoderImg.hidden = YES;
            self.titleLabel.hidden = YES;
            
        }else{
            
       //     self.tableView.mj_footer.hidden = YES;
            
            self.placehoderImg.hidden = NO;
            self.titleLabel.hidden = NO;
        }
        
//        if (self.maintenanceArray.count <= 3) {
//            
//            self.tableView.mj_footer.hidden = YES;
//        }

        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        [self.tableView reloadData];
        
        [MBProgressHUD hideHUDForView:self.view];
        
    } Fail:^(NSString *errorDes) {
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        [MBProgressHUD hideHUD];
        
        [MBProgressHUD hideHUDForView:self.view];
        
    } param:parms ];
    
}

@end
